package com.tanhua.dubbo.server.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.api.UserLikeApi;
import com.tanhua.dubbo.server.pojo.UserLike;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service(version = "1.0.0")
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public static final String LIKE_REDIS_KEY_PREFIX = "USER_LIKE_";

    public static final String NOT_LIKE_REDIS_KEY_PREFIX = "USER_NOT_LIKE_";

    /**
     * 喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public Boolean likeUser(Long userId, Long likeUserId) {
        //判断该用户是否已经喜欢，如果已经喜欢就返回
        if (this.isLike(userId, likeUserId)) {
            return false;
        }

        UserLike userLike = new UserLike();
        userLike.setId(ObjectId.get());
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setCreated(System.currentTimeMillis());

        //保存喜欢的数据到MongoDB中
        this.mongoTemplate.save(userLike);

        //保存喜欢的数据到Redis中
        String redisKey = this.getLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        //查看是否喜欢用户在不喜欢的列表中，如果在，删除数据
        if (this.isNotLike(userId, likeUserId)) {
            redisKey = this.getNotLikeRedisKey(userId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        }


        return true;
    }

    /**
     * 不喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public Boolean notLikeUser(Long userId, Long likeUserId) {
        //判断是否已经不喜欢
        if (this.isNotLike(userId, likeUserId)) {
            return false;
        }
        //为了减少MongoDB的压力，减少IO，不喜欢的数据（不是很重要）不在保存到MongoDB中，
        //保存不喜欢的数据到Redis中
        String redisKey = this.getNotLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

        //查看是否在 喜欢列表中，如果是，删除
        if (this.isLike(userId, likeUserId)) {
            //删除MongoDB中的数据
            Query query = Query.query(Criteria.where("userId").is(userId)
                    .and("likeUserId").is(likeUserId));
            this.mongoTemplate.remove(query,UserLike.class);
            //删除Redis中的数据
            redisKey = this.getLikeRedisKey(userId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
        }
        return true;
    }

    /**
     * 是否相互喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    @Override
    public Boolean isMutualLike(Long userId, Long likeUserId) {
        boolean flag = this.isLike(userId, likeUserId) &&
                this.isLike(likeUserId, userId);
        return flag;
    }

    /**
     * 查询喜欢列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> queryLikeList(Long userId) {
        String redisKey = this.getLikeRedisKey(userId);
        Set<Object> keys = this.redisTemplate.opsForHash().keys(redisKey);
        if (CollUtil.isEmpty(keys)){
            return ListUtil.empty();
        }
        List<Long> result = new ArrayList<>();
        /*for (Object key : keys) {
            result.add(Convert.toLong(key));
        }*/
        keys.forEach(key -> result.add(Convert.toLong(key)));
        return result;
    }

    /**
     * 查询不喜欢列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<Long> queryNotLikeList(Long userId) {
        String redisKey = this.getNotLikeRedisKey(userId);
        Set<Object> keys = this.redisTemplate.opsForHash().keys(redisKey);
        if (CollUtil.isEmpty(keys)){
            return ListUtil.empty();
        }
        List<Long> result = new ArrayList<>();
        /*for (Object key : keys) {
            result.add(Convert.toLong(key));
        }*/
        keys.forEach(key -> result.add(Convert.toLong(key)));
        return result;
    }

    /**
     * 互相喜欢的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Long queryMutualLikeCount(Long userId) {
        //优先从Redis中查询
        //查询我喜欢的列表
        List<Long> likeList = this.queryLikeList(userId);

        Long count = 0L;
        for (Long likeId : likeList) {
            String redisKey = this.getLikeRedisKey(likeId);
            String hashKey = String.valueOf(userId);
            Boolean flag = this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
            if (flag){
                count ++;
            }
        }
        return count;
    }

    /**
     * 喜欢数量
     *
     * @param userId
     * @return
     */
    @Override
    public Long queryLikeCount(Long userId) {
        //优先从Redis中查询
        String redisKey = this.getLikeRedisKey(userId);
        Long count = this.redisTemplate.opsForHash().size(redisKey);
        return count;
    }

    /**
     * 粉丝的数量
     *
     * @param userId
     * @return
     */
    @Override
    public Long queryFanCount(Long userId) {
        //无法从Redis中查询
        Query query = Query.query(Criteria.where("likeUserId").is(userId));
        long count = this.mongoTemplate.count(query, UserLike.class);
        return count;
    }

    /**
     * 查询互相喜欢的列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<UserLike> queryMutualLikeList(Long userId, Integer page, Integer pageSize) {
        List<Long> likeUserIdList = this.queryLikeList(userId);

        Query query = Query.query(Criteria.where("userId").in(likeUserIdList).
                    and("likeUserId").is(userId));

        return this.getPageInfo(query, page, pageSize);
    }

    /**
     * 查询喜欢列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<UserLike> queryLikeList(Long userId, Integer page, Integer pageSize) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        return this.getPageInfo(query, page, pageSize);
    }

    /**
     * 查询粉丝列表
     *
     * @param userId
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public PageInfo<UserLike> queryFanList(Long userId, Integer page, Integer pageSize) {
        Query query = Query.query(Criteria.where("likeUserId").is(userId));
        return this.getPageInfo(query, page, pageSize);
    }

    private PageInfo<UserLike> getPageInfo(Query query, Integer page, Integer pageSize){
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Order.desc("created")));
        query.with(pageRequest);
        List<UserLike> userLikeList = this.mongoTemplate.find(query, UserLike.class);
        PageInfo<UserLike> pageInfo = new PageInfo<>();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);
        pageInfo.setRecords(userLikeList);
        return pageInfo;
    }

    /**
     * 获取喜欢数据的redis key
     *
     * @param userId
     * @return
     */
    private String getLikeRedisKey(Long userId) {
        return LIKE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 获取不喜欢数据的redis key
     *
     * @param userId
     * @return
     */
    private String getNotLikeRedisKey(Long userId) {
        return NOT_LIKE_REDIS_KEY_PREFIX + userId;
    }

    /**
     * 是否喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    public Boolean isLike(Long userId, Long likeUserId) {
        String redisKey = getLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        Boolean flag = this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
        return flag;
    }

    /**
     * 是否不喜欢
     *
     * @param userId
     * @param likeUserId
     * @return
     */
    private Boolean isNotLike(Long userId, Long likeUserId) {
        String redisKey = getNotLikeRedisKey(userId);
        String hashKey = String.valueOf(likeUserId);
        Boolean flag = this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
        return flag;
    }
}
